package ginx

import (
	"gitee.com/chewel/hermes/pkg/journal"
	"github.com/gin-gonic/gin"
)

func Unpack(logger journal.ILogger, fn func(*gin.Context) (any, error)) gin.HandlerFunc {
	return func(c *gin.Context) {
		result, err := fn(c)
		handleErrorAndResponse(c, logger, result, err)
	}
}

func UnpackDefault[T any](logger journal.ILogger, fn func(*gin.Context, T) (any, error)) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req T
		if err := c.ShouldBind(&req); err != nil {
			logger.Error("参数绑定错误", journal.Error(err))
			BadRequest(c, "参数错误")
			return
		}
		result, err := fn(c, req)
		handleErrorAndResponse(c, logger, result, err)
	}
}

func UnpackQuery[T any](logger journal.ILogger, fn func(*gin.Context, T) (any, error)) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req T
		if err := c.ShouldBindQuery(&req); err != nil {
			logger.Error("参数绑定错误", journal.Error(err))
			BadRequest(c, "参数错误")
			return
		}

		result, err := fn(c, req)
		handleErrorAndResponse(c, logger, result, err)
	}
}

func UnpackPath[T any](logger journal.ILogger, fn func(*gin.Context, T) (any, error)) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req T
		if err := c.ShouldBindUri(&req); err != nil {
			logger.Error("参数绑定错误", journal.Error(err))
			BadRequest(c, "参数错误")
			return
		}
		result, err := fn(c, req)
		handleErrorAndResponse(c, logger, result, err)
	}
}

func handleErrorAndResponse(c *gin.Context, logger journal.ILogger, result any, err error) {
	if err != nil {
		logger.Error("系统错误", journal.Error(err))
		Error(c, err)
		return
	}
	OK(c, result)
}
